package com.web.my12306.util;

import com.web.my12306.pojo.AccessPrivilege;
import com.web.my12306.pojo.CommonConstants;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

public class SessionValidatorFilter implements Filter
{
    /**
     * 可用路径
     */
    Set<String> ACCESS_PRIVILEGES= new HashSet<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {

        //登录界面，管理员登录界面
        ACCESS_PRIVILEGES.add(CommonConstants.BASEPATH+"Admin/doLogin");
        ACCESS_PRIVILEGES.add(CommonConstants.BASEPATH+"Admin/ValidateCode");

    }

    /**
     * @author 作者姓名
     * @param orequest 原始请求
     * @param response 原始相应
     * @param chain 访问链
     */
    @Override
    public void doFilter(ServletRequest orequest, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)orequest;
        //编码过滤
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        // 从 Session 获取名为 privileges 的对象 其类型为 AccessPrivilege

        Object oAccessPrivilege = request.getSession().getAttribute(CommonConstants.SESSION_PRIVILEGES);
        String uri = request.getRequestURI();
        //        System.out.println(uri);
        if (ACCESS_PRIVILEGES.contains(uri)) {
            chain.doFilter(request,response);
        }

        else if (oAccessPrivilege != null) {
            // 已登陆状态，进一步判断权限
            AccessPrivilege accessPrivilege = (AccessPrivilege)oAccessPrivilege;

            // 如果是根用户授权，则直接放行
            if (accessPrivilege.isRootUser()) {
                chain.doFilter(request,response);
            }
            else {


                // 如果当前用户授权包含此URI，则放行
                if (accessPrivilege.isLegal(uri)) {
                    chain.doFilter(request,response);
                }
                else {
                    // 访问的URI未授权，跳转到登录页面
                    request.getRequestDispatcher("/error.html").forward(request, response);
                }
            }
        }
        else {
            // 未登陆状态，跳转到登陆页面
            request.getRequestDispatcher("/error.html").forward(request, response);
        }
    }

    @Override
    public void destroy() {

    }

}
